package v1

import (
	"banzhuan-sys/model"
	"banzhuan-sys/pkg/db"
	"banzhuan-sys/pkg/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gocolly/colly"
	"log"
	"net/http"
	"strconv"
	"sync"
)

// @Summary 修改文章标签
// @Produce  json
// @Param id path int true "ID"
// @Param name query string true "ID"
// @Param state query int false "State"
// @Param modified_by query string true "ModifiedBy"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /api/v1/tags/{id} [put]
func GetIps(ctx *gin.Context) {


	startUrl := "http://www.ip3366.net/free"


	c := colly.NewCollector(
		colly.UserAgent(utils.RandomUA()),
		colly.MaxDepth(10),
	)

	c.Limit(&colly.LimitRule{
		DomainGlob:  "*",
		//Delay: 5 * time.Second,
	})



	c.OnError(func(response *colly.Response, e error) {

		//log.Println(e.Error())

	})


	c.OnRequest(func(request *colly.Request) {
		log.Println("start url:",request.URL.String())
	})

	//c1.OnResponse(func(response *colly.Response) {
	//	 log.Println(string(response.Body))
	//})



	c.OnHTML("table>tbody", func(element *colly.HTMLElement) {

		var ipPools []model.IpPool

		element.ForEach("tr", func(i int, element *colly.HTMLElement) {

			ipPool := model.IpPool{}


			element.ForEach("td", func(i int, element *colly.HTMLElement) {


				switch i {
				case 0:
					ipPool.Ip = element.Text
					break
				case 1:
					ipPool.Port = element.Text
					break
				case 3:
					if element.Text == "HTTP" {
						ipPool.SType = 1
					}else{
						ipPool.SType = 2
					}
				default:
					break
				}




			})

			ipPools = append(ipPools,ipPool)


		})
		db.My.Create(&ipPools)


	})

	c.OnHTML("#listnav>ul a", func(element *colly.HTMLElement) {

		if page, err := strconv.Atoi(element.Text) ;err == nil && page <= 3 && page > 1{
			log.Println(element.Attr("href"))
			element.Request.Visit(element.Attr("href"))
		}

	})



	c.Visit(startUrl)


}

func CheckPool(ctx *gin.Context)  {


	var ipPools []model.IpPool

	res := db.My.Find(&ipPools)

	if err := res.Error; err != nil {
		panic(err)
	}

	var wg sync.WaitGroup
	for _, value := range ipPools {


		wg.Add(1)
		go func(value model.IpPool) {

			defer wg.Done()
			re := utils.CheckIp(value.Ip,value.Port,value.SType)
			fmt.Println(value.Ip+":",re)
		}(value)

	}

	wg.Wait()

}

func CheckOIp(ctx *gin.Context)  {


	ip := ctx.Query("ip")
	port := ctx.Query("port")
	stype,_ := strconv.Atoi(ctx.Query("stype"))




	re := utils.CheckIp(ip,port, stype)


	ctx.JSON(http.StatusOK, gin.H{
		"code": "0000",
		"msg": "ok",
		"data":re,
	})

}
